package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.RegexUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 新增医生
 */
public class DoctorAddActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private EditText userName,phone,idNumber,age,address,specialty,describe;

    private RadioButton man,woman;

    private Spinner positionType,departmentsType;

//    声明全局医生职务和所属科室
    private String positionTypeToStr,departmentsTypeToStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_add);
//        实例化
        dbOpenHelper = new DBOpenHelper(DoctorAddActivity.this, "db_kindheartedness", null, 1);
        //        获取按钮控制权
        Button doctorRegisterBtn = findViewById(R.id.doctorRegisterBtn);
        doctorRegisterBtn.setOnClickListener(this);
//        获取采购员信息控制权
        userName = findViewById(R.id.userName);
        phone = findViewById(R.id.phone);
        idNumber = findViewById(R.id.idNumber);
        age = findViewById(R.id.age);
        address = findViewById(R.id.address);
        specialty = findViewById(R.id.specialty);
        describe = findViewById(R.id.describe);
//         获取性别控制权
        man = findViewById(R.id.man);
        woman = findViewById(R.id.woman);
        positionType = findViewById(R.id.positionType);
        departmentsType = findViewById(R.id.departmentsType);

//        进行所有职务下拉框赋值
        findAllPosition();
//        进行所有二级科室下拉框赋值
        findAllDepartments();
        positionType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                positionTypeToStr = (String) positionType.getSelectedItem();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        departmentsType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                departmentsTypeToStr = (String) departmentsType.getSelectedItem();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

    }

    /**
     * 查询所有二级科室
     */
    private void findAllDepartments() {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor query = readableDatabase.query("departments", null, "departments_id != ?", new String[]{"0"}, null, null, null);
        List<String> departmentsList = new ArrayList<>(10);
        while (query.moveToNext()) {
            String departmentsName = query.getString(1);
            departmentsList.add(departmentsName);
        }
        setSpinnerText(departmentsType,departmentsList);

    }

    /**
     * 查询所有职务
     */
    private void findAllPosition() {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor query = readableDatabase.query("position", null, null, null, null, null, null);
        List<String> positionList = new ArrayList<>(6);
        while (query.moveToNext()) {
            String positionName = query.getString(1);
            positionList.add(positionName);
        }
        setSpinnerText(positionType,positionList);
    }

    /**
     * 下拉框赋值
     * @param spinner 下拉框
     * @param positionList 数据集
     */
    public void setSpinnerText(Spinner spinner, List<String> positionList){
        ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,positionList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);//给下拉框赋值
    }


    /**
     * 按钮点击事件
     * @param v
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            新增医生
            case R.id.doctorRegisterBtn:
                addDoctor();
                break;
            default:

        }
    }

    /**
     * 新增医生
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void addDoctor() {
        String doctorUserName = userName.getText().toString();
        String doctorPhone = phone.getText().toString();
        String doctorIdNumber = idNumber.getText().toString();
        String doctorAge = age.getText().toString();
//        判断选择的性别
        String doctorSex = "0";
        if (woman.isChecked()) {
            doctorSex = "1";
        }
        String doctorAddress = address.getText().toString();
        String doctorSpecialty = specialty.getText().toString();
        String doctorDescribe = describe.getText().toString();
        Boolean check = checkBuyerData(doctorUserName,doctorPhone,doctorIdNumber,doctorAge,doctorSex,doctorAddress,doctorSpecialty,doctorDescribe);
        if (check) { //校验通过
//        打开数据库
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        校验职务是否存在
            Integer positionId = null;
            Cursor query = readableDatabase.query("position", null, "name = ?", new String[]{positionTypeToStr}, null, null, null);
            while (query.moveToNext()) {
                try {
                    positionId = Integer.valueOf(query.getString(0));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("DockerAddActivity.java", "数据不能转化为数字,请检查！");
                }
            }
//          检查医生所属科室
            Integer departmentsId = null;
            Cursor queryDepartments = readableDatabase.query("departments", null, "name = ?", new String[]{departmentsTypeToStr}, null, null, null);
            while (queryDepartments.moveToNext()) {
                try {
                    departmentsId = Integer.valueOf(queryDepartments.getString(0));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("DockerAddActivity.java", "数据不能转化为数字,请检查！");
                }
            }
            //                    封装需要新增的医生详情信息
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",doctorUserName);
            contentValues.put("position_id",positionId);
            contentValues.put("departments_id",departmentsId);
            contentValues.put("specialty",doctorSpecialty);
            contentValues.put("describe",doctorDescribe);
            contentValues.put("create_time", DateUtil.dateString(new Date()));
            contentValues.put("update_time", DateUtil.dateString(new Date()));
            long doctorDetailsId = readableDatabase.insert("doctor_details", null, contentValues);
//                    封装需要新增的医生用户信息
            ContentValues contentUserValues = new ContentValues();
            contentUserValues.put("username",doctorUserName);
            contentUserValues.put("phone",doctorPhone);
            contentUserValues.put("password","123456"); // 默认密码
            contentUserValues.put("type",1); // 1:医生
            contentUserValues.put("sex",doctorSex);
            contentUserValues.put("age",doctorAge);
            contentUserValues.put("id_number",doctorIdNumber);
            contentUserValues.put("address",doctorAddress);
            contentUserValues.put("doctor_id",doctorDetailsId);
            contentUserValues.put("create_time", DateUtil.dateString(new Date()));
            contentUserValues.put("update_time", DateUtil.dateString(new Date()));
            long userId = readableDatabase.insert("user", null, contentUserValues);
            if (userId > 0 && doctorDetailsId > 0) {
                toast = ToastUtil.toastHint(toast, DoctorAddActivity.this, "新增医生成功，请稍后查看！");
                return;
            }
        }

    }

    /**
     * 校验医生信息
     * @param doctorUserName 名称
     * @param doctorPhone 手机号
     * @param doctorIdNumber 身份证号
     * @param doctorAge 年龄
     * @param doctorSex 性别
     * @param doctorAddress 地址
     * @param doctorSpecialty 擅长
     * @param doctorDescribe 简介
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private Boolean checkBuyerData(String doctorUserName, String doctorPhone, String doctorIdNumber, String doctorAge, String doctorSex, String doctorAddress, String doctorSpecialty, String doctorDescribe) {
        if (!RegexUtil.checkChinese(doctorUserName)) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"医生姓名只支持中文！");
            return false;
        }
        if (!RegexUtil.checkMobile(doctorPhone)) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请输入正确的手机号！");
            return false;
        }
        if (!RegexUtil.checkIdCard(doctorIdNumber)) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请输入正确的身份证号！");
            return false;
        }
        if (!RegexUtil.checkDigitz(doctorAge)) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请输入正确的年龄！");
            return false;
        }
        if (!doctorSex.equals("0") && !doctorSex.equals("1")) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请选择性别！");
            return false;
        }
        if (doctorAddress.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请输入地址！");
            return false;
        }

        if (doctorSpecialty.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请输入擅长！");
            return false;
        }

        if (doctorDescribe.equals("")) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"请输入简介！");
            return false;
        }

        //        校验信息是否存在
//        打开数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        校验手机号是否已被注册
        String buyerId = null;
        Cursor query = readableDatabase.query("user", null, "phone = ?", new String[]{doctorPhone}, null, null, null);
        while (query.moveToNext()) {
            buyerId = query.getString(0);
        }
//        如果存在值，表示已经被注册
        if (Objects.nonNull(buyerId)) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"该手机号已被注册！");
            return false;
        }
        //        校验身份证号是否已被注册
        String buyerId2 = null;
        Cursor query2 = readableDatabase.query("user", null, "id_number = ?", new String[]{doctorIdNumber}, null, null, null);
        while (query2.moveToNext()) {
            buyerId2 = query2.getString(0);
        }
//        如果存在值，表示已经被注册
        if (Objects.nonNull(buyerId2)) {
            toast = ToastUtil.toastHint(toast,DoctorAddActivity.this,"该身份证号已被注册！");
            return false;
        }

        return true;
    }

    /**
     * 重写onKeyDown()方法来拦截用户单击后退按钮事件
     * @param keyCode 按键标识
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            返回上一页标识是否刷新
//            setResult(RESULT_OK,new Intent());
//            重新跳转到医生管理页
            startActivityForResult(new Intent(DoctorAddActivity.this,DockerAdminActivity.class),RESULT_OK);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}